﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCMS.UI.Models;
using SCMS.Model;
using SCMS.CoreBusinessLogic.Web;
using SCMS.CoreBusinessLogic.ActionFilters;
using SCMS.CoreBusinessLogic.Security;
using SCMS.CoreBusinessLogic.TenderAnalysis;
using SCMS.CoreBusinessLogic.OrderRequest;
using System.Text;
using SCMS.UI.GeneralHelper;
using SCMS.CoreBusinessLogic.TravelAuthorisation;
using System.Data.Objects.DataClasses;
using SCMS.CoreBusinessLogic.NotificationsManager;

namespace SCMS.UI.Controllers
{
    [MyException]
    public class TravelAuthController : PortalBaseController
    {
        private ITAnalysisService taService;
        private IOrderRequest oRService;
        private ITravelAuthService TAuthService;
        private INotificationService notificationService;

        public TravelAuthController(IPermissionService permissionService, IUserContext userContext, ITAnalysisService taService,
            IOrderRequest oRService, ITravelAuthService TAuthService, INotificationService notificationService)
            : base(userContext, permissionService)
        {
            this.taService = taService;
            this.oRService = oRService;
            this.TAuthService = TAuthService;
            this.notificationService = notificationService;
        }
        //
        // GET: /TravelAuth/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult LoadTAuth()
        {
            var model = new TravelAuth()
            {
                EntityTravelAuth = new TravelAuthorization(),
                staffs = new SelectList(taService.GetStaffs(countryProg.Id), "StaffID", "StaffName"),
                TravelDates = new List<Model.TravelDate>(),
                TravelExpense = new List<Model.TravelExpense>(),
                Currencies = new SelectList(oRService.GetCurrencies(countryProg.Id), "Id", "ShortName")
            };
            model.EntityTravelAuth.RefNumber = "--New TAF--";
            ViewBag.Proceed = false;
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ProceedToTAuthDetails(Models.TravelAuth TAmodel)
        {
            ViewBag.Proceed = true;
            TAmodel.EntityTravelAuth.TotalAmount = 0;
            TAmodel.EntityTravelAuth.Id = Guid.NewGuid();
            TAmodel.EntityTravelAuth.PreparedBy = currentStaff.Id;
            TAmodel.EntityTravelAuth.CountryProgrammeId = countryProg.Id;
            var model = new TravelAuth()
            {
                EntityTravelAuth = TAmodel.EntityTravelAuth,
                staffs = new SelectList(taService.GetStaffs(countryProg.Id), "StaffID", "StaffName"),
                TravelDates = new List<Model.TravelDate>(),
                TravelExpense = new List<Model.TravelExpense>(),
                Currencies = new SelectList(oRService.GetCurrencies(countryProg.Id), "Id", "ShortName")
            };
            ViewBag.TAuthId = TAmodel.EntityTravelAuth.Id;
            UserSession.CurrentSession.TravelAuth = TAmodel.EntityTravelAuth;
            return View("LoadTAuth", model);
        }

        public ActionResult LoadTravelDate(Guid TAuthId)
        {
            var model = new Models.TravelDate()
            {
                EntityTDate = new Model.TravelDate(),
                Currencies = new SelectList(oRService.GetCurrencies(countryProg.Id), "Id", "ShortName"),
                ProjectNos = new SelectList(oRService.GetProjectNos(countryProg.Id), "Id", "ProjectNumber"),
                BudgetLines = new SelectList(oRService.GetProjectBugdetLines(Guid.Empty))
            };

            ViewBag.TAuthId = TAuthId;
            return View(model);
        }

        public ActionResult SaveTADates(Models.TravelDate TAuthDAtes)
        {
            TAuthDAtes.EntityTDate.TravelAuthorizationId = TAuthDAtes.TravelAuthorizationId;
            if (TAuthService.SaveTravalAuth(UserSession.CurrentSession.TravelAuth, TAuthDAtes.EntityTDate))
                UserSession.CurrentSession.TravelAuth = null;
            return PrepareTAuthDates(TAuthDAtes.TravelAuthorizationId);
        }

        public ActionResult LoadTravelExpense(Guid TAuthId)
        {
            var model = new Models.TravelExpense()
            {
                EntityTExpense = new Model.TravelExpense(),
                Currencies = new SelectList(oRService.GetCurrencies(countryProg.Id), "Id", "ShortName"),
                ProjectNos = new SelectList(oRService.GetProjectNos(countryProg.Id), "Id", "ProjectNumber"),
                BudgetLines = new SelectList(oRService.GetProjectBugdetLines(Guid.Empty))
            };
            ViewBag.TAuthId = TAuthId;
            return View(model);
        }

        public ActionResult SaveTAExpense(Models.TravelExpense TAExpensemodel)
        {
            TAExpensemodel.EntityTExpense.TravelAuthorizationId = TAExpensemodel.TravelAuthorizationId;
            if (TAuthService.SaveTravalAuth(UserSession.CurrentSession.TravelAuth, TAExpensemodel.EntityTExpense))
                UserSession.CurrentSession.TravelAuth = null;
            return PrepareTAuth(TAExpensemodel.TravelAuthorizationId);
        }

        private ActionResult PrepareTAuth(Guid TravelAuthorizationId)
        {
            using (var db = new SCMSEntities())
            {
                StringBuilder blinOption = new StringBuilder();
                Model.TravelAuthorization Tauth = db.TravelAuthorizations.FirstOrDefault(p => p.Id == TravelAuthorizationId);
                foreach (var item in Tauth.TravelExpenses)
                {
                    blinOption.Append("<tr><td>");
                    blinOption.Append(item.ExpenseDescription);
                    blinOption.Append("</td><td align=\"right\">");
                    blinOption.Append(item.TotalCost.Value.ToString("##,##0.00"));
                    blinOption.Append("</td><td align=\"right\">");
                    blinOption.Append(item.AdvanceRequired.Value.ToString("##,##0.00"));
                    blinOption.Append("</td><td>");
                    blinOption.Append(item.Currency.ShortName);
                    blinOption.Append("</td><td>");
                    blinOption.Append(item.ProjectBudget.BudgetCategory.ProjectDonor.ProjectNumber);
                    blinOption.Append("</td><td>");
                    blinOption.Append(item.ProjectBudget.LineNumber);
                    blinOption.Append("</td></tr>");
                }
                ViewBag.Html = blinOption.ToString();
                return View("HTMLResponse");
            }
        }

        private ActionResult PrepareTAuthDates(Guid TravelAuthorizationId)
        {
            using (var db = new SCMSEntities())
            {
                StringBuilder blinOption = new StringBuilder();
                Model.TravelAuthorization Tauth = db.TravelAuthorizations.FirstOrDefault(p => p.Id == TravelAuthorizationId);
                foreach (var item in Tauth.TravelDates)
                {
                    blinOption.Append("<tr><td align=\"center\">");
                    blinOption.Append(item.TravalDate.Value.ToShortDateString());
                    blinOption.Append("</td><td>");
                    blinOption.Append(item.Destination);
                    blinOption.Append("</td><td>");
                    blinOption.Append(item.NoOfNights);
                    blinOption.Append("</td><td align=\"right\">");
                    blinOption.Append(item.DailyPDRate.Value.ToString("##,##0.00"));
                    blinOption.Append("</td><td align=\"right\">");
                    blinOption.Append(item.TotalAllowance.Value.ToString("##,##0.00"));
                    blinOption.Append("</td><td align=\"right\">");
                    blinOption.Append(item.AdvanceRequired.Value.ToString("##,##0.00"));
                    blinOption.Append("</td><td>");
                    blinOption.Append(item.Currency.ShortName);
                    blinOption.Append("</td><td>");
                    blinOption.Append(item.ProjectBudget.BudgetCategory.ProjectDonor.ProjectNumber);
                    blinOption.Append("</td><td>");
                    blinOption.Append(item.ProjectBudget.LineNumber);
                    blinOption.Append("   </td></tr>");
                }
                ViewBag.Html = blinOption.ToString();
                return View("HTMLResponse");
            }
        }

        public ActionResult GetBudgetLineForTAuthExpense(Guid id)
        {
            //# is a placeholder that will be replaced on the other side
            StringBuilder blinOption = new StringBuilder();
            blinOption.Append("<select id=\"EntityTExpense_BudgetLineId\" name=\"EntityTExpense.BudgetLineId\">");
            List<Model.BudgetLineView> BLines = oRService.GetProjectBugdetLines(id);
            foreach (BudgetLineView item in BLines)
                blinOption.Append("<option value=\"" + item.Id + "\">" + item.Description + "</option>");
            blinOption.Append("</select>");
            blinOption.Append("<span class=\"field-validation-valid\" data-valmsg-for=\"EntityTExpense.BudgetLineId\" data-valmsg-replace=\"true\"></span>");
            ViewBag.Html = blinOption.ToString();
            return View("HTMLResponse");
        }

        public ActionResult GetBudgetLineForTAuthDates(Guid id)
        {
            //# is a placeholder that will be replaced on the other side
            StringBuilder blinOption = new StringBuilder();
            blinOption.Append("<select id=\"EntityTDate_BudgetLineId\" name=\"EntityTDate.BudgetLineId\">");
            List<Model.BudgetLineView> BLines = oRService.GetProjectBugdetLines(id);
            foreach (BudgetLineView item in BLines)
                blinOption.Append("<option value=\"" + item.Id + "\">" + item.Description + "</option>");
            blinOption.Append("</select>");
            blinOption.Append("<span class=\"field-validation-valid\" data-valmsg-for=\"EntityTDate.BudgetLineId\" data-valmsg-replace=\"true\"></span>");
            ViewBag.Html = blinOption.ToString();
            return View("HTMLResponse");
        }

        public ActionResult GetBudgetLinesForTAAuth(Guid id, bool isDate, int index)
        {
            string selectId = "", selectName = "";
            int _isDate = 0;
            if (isDate)
            {
                selectId = "ViewTravelDates_#__EntityTDate_BudgetLineId";
                selectName = "ViewTravelDates[#].EntityTDate.BudgetLineId";
                _isDate = 1;
            }
            else
            {
                selectId = "ViewTravelExpenses_#__EntityTExpense_BudgetLineId";
                selectName = "ViewTravelExpenses[#].EntityTExpense.BudgetLineId";
            }
            //# is a placeholder that will be replaced on the other side
            StringBuilder blinOption = new StringBuilder();
            blinOption.Append("<select id=\"" + selectId + "\" name=\"" + selectName + "\" onchange = \"javascript:checkBalance4TAF(this, " + index + ", " + _isDate + ")\">");
            List<Model.BudgetLineView> BLines = oRService.GetProjectBugdetLines(id);
            foreach (BudgetLineView item in BLines)
                blinOption.Append("<option value=\"" + item.Id + "\">" + item.Description + "</option>");
            blinOption.Append("</select>");
            ViewBag.Html = blinOption.ToString();
            return View("HTMLResponse");
        }

        public ActionResult SubmitTAF(Guid Id)
        {
            Model.TravelAuthorization TAF = TAuthService.GetTAFById(Id);
            TAF.IsRejected = false;
            TAF.IsReviewed = false;
            TAF.IsAuthorized = false;
            TAF.IsSubmitted = true;
            TAF.PreparedBy = currentStaff.Id;
            TAF.PreparedOn = DateTime.Now;
            TAF.RefNumber = TAuthService.GenerateUniquNumber(countryProg);
            TAuthService.SubmitTAF(TAF);
            return ViewTravelAuthForms();
        }

        public ActionResult ViewTravelAuthForms()
        {
            using (var db = new SCMSEntities())
            {
                List<Models.ViewTAForms> model = new List<ViewTAForms>();

                foreach (var item in TAuthService.GetTAuthForms(countryProg.Id))
                {

                    var modelItem = new ViewTAForms()
                        {
                            TAuthFormEntity = item,
                            Travelller = db.VStaffDetails.FirstOrDefault(p => p.StaffID == item.TravellerId)
                        };
                    model.Add(modelItem);
                }
                return View("ViewTravelAuthForms", model);
            }
        }

        public ActionResult ViewTravelAuthFormsDetails(Guid id)
        {
            ViewTAForms model = TAFExtention.PrepareTAF(id);
            //Manage approval link
            string actionType = null;
            if ((bool)model.TAuthFormEntity.IsReviewed && !(bool)model.TAuthFormEntity.IsAuthorized)
                actionType = NotificationHelper.authorizationCode;
            else if ((bool)model.TAuthFormEntity.IsSubmitted && !(bool)model.TAuthFormEntity.IsReviewed)
                actionType = NotificationHelper.reviewCode;
            if (actionType != null)
                model.CanApprove = notificationService.CanApprove(currentUser, NotificationHelper.tafCode, actionType, model.TAuthFormEntity.Id);
            else
                model.CanApprove = false;
            return View(model);
        }
    }
}
